package com.tian.recycler.itemtouch

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.tian.recycler.R
import com.tian.recycler.holder.BaseHolder
import java.util.*

/**
 * @author tiansongtao, Email:tiansongtao@up366.com
 * @date 2021/3/22 10:00
 */
class ItemTouchAdapter(var data: MutableList<String>) : RecyclerView.Adapter<BaseHolder>(), ItemTouchAdapterCallback {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_touch_text, null)
        view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        return BaseHolder(view)
    }

    override fun onBindViewHolder(holder: BaseHolder, position: Int) {
        holder.itemView.findViewById<TextView>(R.id.tv_text).text = "${data[position]} $position"
    }

    override fun getItemCount() = data.size


    override fun onItemMove(fromPosition: Int, toPosition: Int) {
        Collections.swap(data, fromPosition, toPosition)
        notifyItemMoved(fromPosition, toPosition)
    }

    override fun onItemDelete(viewHolder: RecyclerView.ViewHolder) {
        data.removeAt(viewHolder.adapterPosition)
        notifyItemRemoved(viewHolder.adapterPosition)
    }


}